import { Component, OnInit } from '@angular/core';
import { Carousel } from '../../model/carousel';
import { NewsService } from '../../service/news.service';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { TranslationWidth } from '@angular/common';
import { CarouselService } from '../../service/carousel.service';
@Component({
  selector: 'app-editcarousel',
  templateUrl: './editcarousel.component.html',
  styleUrls: ['./editcarousel.component.css']
})
export class EditcarouselComponent implements OnInit {
  carousel:Carousel;
  parm:string;
  selectedFile:string;

  constructor(
    private http:HttpClient,
    private router:Router,
    private routerinfo:ActivatedRoute,
    private carouselservice:CarouselService,
  ) { 
this.carousel=new Carousel();
this.parm=this.routerinfo.snapshot.params['id'];
  }

  ngOnInit() {
    if(this.parm=='add'){
      this.carousel=new Carousel();
    }else{
      this.getCarousel(this.parm);
    }
  }

//   save(){
            
//     this.carouselservice.addCarousel(this.carousel)
//     .then((flag:boolean)=>{
// if(flag==true){

//   alert('成功');
// }
// else{
//   alert('失败');
// }
//     })
//   }
save(){
  if(this.parm=='add'){
    this.addCarousel();
  }
  else{
    this.updateCarousel();
  }
}


goBack(){

  this.router.navigate(['uploadfile']);

  }


  onFileChanged(event) {
    this.selectedFile = event.target.files[0];
  }


  onUpload() {

    const uploadData = new FormData();
  uploadData.append('file', this.selectedFile);


  this.http.post('http://www.baotr.xyz:81/manage/fileUpload',uploadData).subscribe(
    (data:any)=>{
 let host="http://www.baotr.xyz:81/public/";
 this.carousel.pic=host+data.pic;

    },(err:HttpErrorResponse)=>{
      console.log(err.message);
    }
  )

  }

  private addCarousel(){

    this.carouselservice.addCarousel(this.carousel).then((flag:boolean)=>{
      if(flag==true){
        this.goBack();
      }
      else{
        alert('保存异常，请刷新后重试')
      }
    })
  }




  private updateCarousel(){
    this.carouselservice.updateNews(this.carousel)
    .then((flag)=>{
      if(flag==true){
        this.goBack();
      }else{
        alert("保存异常，请刷新重试");
      }
    })
  }

  private getCarousel(id:string){
    this.carouselservice.getCarousel(id)
    .then((data:Carousel)=>{
      if(data){
        this.carousel=data;
      }else{
        alert("参数异常，请刷新后重试");
      }
    })
  }

}
